#include "Block.h"
#include <utils\Log.h>
#include "Constants.h"
#include <renderer\DebugRenderer.h>

const float ADD_X[4] = { 0.0f, 35.0f , 35.0f ,  0.0f};
const float ADD_Y[4] = { 0.0f,  0.0f , 35.0f , 35.0f};

Block::Block(Map* map) : ds::SpriteNode("Block","TexturesMaterial") , m_Map(map) {
	rand.seed(GetTickCount());	
}

Block::~Block(void)
{
}

void Block::loadContent( ds::ResManager& resourceManager ) {
	for ( int i = 0; i < 4; ++i ) {
		m_Pieces[i].handle = add(ds::Vec2(200,200),ds::Rect(70,0,32,32));
		setVisible(m_Pieces[i].handle,false);
	}	
	m_Border = add(ds::Vec2(200,200),ds::Rect(72,200,75,75));
	setVisible(m_Border,false);
	updatePosition(ds::Vec2(196,192));
	pickColors();
	
}

void Block::update( float elapsed ) {
	int mx = gEngine->getMousePosX();
	int my = gEngine->getMousePosY();
	int x = ( mx - 100.0f ) / 35;
	int y = ( my - 100.0f ) / 35;
	ds::Vec2 p = ds::Vec2(START_X + x * SQUARE_SIZE,START_Y + y * SQUARE_SIZE);
	updatePosition(p);
	//gEngine->getDebugRenderer()->addText(ds::Vec2(10,50),ds::Color(1.0f,1.0f,1.0f,1.0f),"Block at %d %d",x,y);
}

void Block::pickColors() {
	int firstColor = getRnd();
	int secondColor = getRnd();
	int type = getRnd(5);
	if ( type == 0 ) {
		setColor(0,firstColor);
		setColor(1,firstColor);
		setColor(2,secondColor);
		setColor(3,secondColor);
	}
	else if ( type == 1 ) {
		setColor(0,firstColor);
		setColor(2,firstColor);
		setColor(1,secondColor);
		setColor(3,secondColor);
	}
	else if ( type == 2 ) {
		setColor(0,firstColor);
		setColor(3,firstColor);
		setColor(1,secondColor);
		setColor(2,secondColor);
	}
	else if ( type == 3 ) {
		setColor(3,firstColor);
		setColor(0,firstColor);
		setColor(2,secondColor);
		setColor(1,secondColor);
	}
	else {
		setColor(2,firstColor);
		setColor(0,firstColor);
		setColor(3,secondColor);
		setColor(1,secondColor);
	}
}

void Block::updatePosition(const ds::Vec2& pos) {
	m_Position = pos;	
	if ( m_Position.x < START_X ) {
		m_Position.x = START_X;
	}
	if ( m_Position.y < START_Y ) {
		m_Position.y = START_Y;
	}
	for ( int i = 0; i < 4; ++i ) {
		ds::Vec2 sp = m_Position;
		sp.x += ADD_X[i];
		sp.y += ADD_Y[i];
		setPosition(m_Pieces[i].handle,sp);
	}	
	ds::Vec2 bp = pos;
	bp.sub(4,4);
	setPosition(m_Border,bp);
}

void Block::rotateColors() {
	int lf = getColor(3);
	for ( int i = 3 ; i > 0; --i ) {
		setColor(i,getColor(i-1));
	}
	setColor(0,lf);
}

bool Block::convert() {
	if ( m_Map->addBlock(m_Position,m_Pieces[0].color,m_Pieces[1].color,m_Pieces[2].color,m_Pieces[3].color) ) {
		pickColors();
		return true;
	}
	return false;
}
